<template>
	<view class="search">
		<Lines></Lines>
		<view class='search-item'>
			<view class='search-title'>
				<view class='f-color'>最近搜索</view>
				<view class='iconfont icon-laji_huabanfuben' @click="clearHistory()"></view>
			</view>
			<view v-if="searchData.length>0">
				<view class='search-name f-color' v-for="(item,index) in searchData" :key="index"
					@tap="toSearchList(item)">{{item}}</view>
			</view>
			<view v-else class="search-end">
				暂无搜索记录
			</view>
		</view>

		<view class='search-item'>
			<view class='search-title'>
				<view class='f-color'>热门搜索</view>
			</view>
			<view>
				<view class='search-name f-color'>四件套</view>
				<view class='search-name f-color'>面膜</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import Lines from '@/components/common/Line.vue'
	import {
		onNavigationBarButtonTap,
		onNavigationBarSearchInputChanged,
		onNavigationBarSearchInputConfirmed,
		onLoad,
	} from "@dcloudio/uni-app"
	import {
		ref
	} from 'vue'
	// 输入的内容
	const keyword = ref()
	// 搜索过的关键词
	const searchData = ref([])
	onLoad((e) => {
		uni.getStorage({
			key: 'searchData',
			success: function(res) {
				searchData.value = JSON.parse(res.data)
			}
		})
	})
	// 得到输入的内容
	onNavigationBarSearchInputChanged((e) => {
		keyword.value = e.text
	})
	// 点击搜索执行
	onNavigationBarButtonTap((e) => {
		search()
	})
	// 软键盘
	onNavigationBarSearchInputConfirmed((e) => {
		search()
	})
	// 判断输入内容不能为空
	const search = () => {
		if (keyword.value === "") {
			return uni.showToast({
				title: "关键词不能为空",
				icon: "none"
			})
		} else {
			toSearchList(keyword.value)
		}
		// 隐藏软键盘
		uni.hideKeyboard()
			addSearch()
	}
	const addSearch = () => {
		let idx = searchData.value.indexOf(keyword.value);
		if (idx < 0) {
			searchData.value.unshift(keyword.value);
		} else {
			searchData.value.unshift(searchData.value.splice(idx, 1)[0]);
		}
		uni.setStorage({
			key: "searchData",
			data: JSON.stringify(searchData.value)
		})
	}
	const clearHistory = () => {
		uni.showModal({
			title: "提示",
			content: '是否清除搜索记录',
			cancelText: '取消',
			confirmText: '确定',
			success: (res) => {
				if (res.confirm) {
					uni.removeStorage({
						key: 'searchData',
					})
					searchData.value = []
				}
			}
		})
	}
	const toSearchList = (item) => {
		uni.navigateTo({
			url: "/pages/search-list/search-list?keyword=" + item + ""
		})
	}
</script>


<style scoped>
	.search-item {
		padding: 20rpx;
	}

	.search-title {
		display: flex;
		justify-content: space-between;
	}

	.search-name {
		padding: 4rpx 24rpx;
		background-color: #E1E1E1;
		display: inline-block;
		border-radius: 26rpx;
		margin: 10rpx;
	}

	.search-end {
		text-align: center;
	}
</style>
